import 'dart:async';
import 'package:inmotion_pro/custom_exception/lx_exception.dart';
import 'package:inmotion_pro/l10n/local.dart';
import 'package:inmotion_pro/pages/mixin/cache_mixin.dart';
import 'package:inmotion_pro/service/vehicle_connection_service.dart';
import 'package:ble_helper_plugin/library.dart';
import 'package:flutter/foundation.dart';

mixin BluetoothMixin on CacheMixin {
  // 开始扫描
  bluetoothMixinStartScan(
    Function(List<CustomScanResult>) scanResultsCallback, {
    Duration? timeout,
    VoidCallback? onTimeout,
  }) {
    VechileConnectionService.to.bluetoothConnectHelper?.startScan(
      timeout: timeout ?? const Duration(seconds: 15),
      onTimeout: onTimeout,
      callbackScanResults: (devices) {
        scanResultsCallback(devices);
      },
    );
  }

  // 停止扫描
  Future<void> bluetoothMixinStopScan({
    bool isSkipIdleState = false,
  }) {
    return VechileConnectionService.to.bluetoothConnectHelper!.stopScan(
      isSkipIdleState: isSkipIdleState,
    );
  }

  // 搜索指定的蓝牙设备
  Future<bool> bluetoothMixinSearchTargetDevice(
    String bleName, {
    Duration? timeout,
    VoidCallback? onTimeout,
    Function(CustomScanResult)? callbackScanResults,
  }) {
    return VechileConnectionService.to.bluetoothConnectHelper!.search(
      bleName,
      timeout: timeout,
      onTimeout: onTimeout,
      callbackScanResults: callbackScanResults,
    );
  }

  // 搜索并连接指定的蓝牙设备
  Future<bool> bluetoothMixinSearchAndConnectTargetDevice(
    String bleName, {
    Duration? searchTimeout,
    VoidCallback? searchOnTimeout,
    Duration? connectTimeout,
    VoidCallback? connectOnTimeout,
  }) {
    final completer = Completer<bool>();
    // 搜索指定的蓝牙设备
    bluetoothMixinSearchTargetDevice(
      bleName,
      timeout: searchTimeout ?? const Duration(seconds: 5),
      onTimeout: searchOnTimeout,
      callbackScanResults: (scanResult) {
        // 去连接搜索到的设备
        bluetoothMixinConnectScanResult(
          scanResult,
          isSkipIdleState: true,
        ).then((connectSuccess) {
          if (!completer.isCompleted) {
            completer.complete(connectSuccess);
          }
        }).catchError((error) {
          if (!completer.isCompleted) {
            completer.completeError(error);
          }
        });
      },
    ).then((searchSuccess) {
      debugPrint('搜索指定的蓝牙设备：${searchSuccess ? "成功" : "失败"}');
    }).catchError((error) {
      if (!completer.isCompleted) {
        completer.completeError(error);
      }
      debugPrint('搜索指定的蓝牙设备失败：$error');
    });
    return completer.future;
  }

  // 连接扫描到的设备
  Future<bool> bluetoothMixinConnectScanResult(
    CustomScanResult scanResult, {
    bool isSkipIdleState = false,
  }) {
    return _startConnectBluetooth(
      scanResult,
      isSkipIdleState: isSkipIdleState,
    ).then((connectSuccess) {
      if (connectSuccess) {
        return VechileConnectionService.to.business!
            .vehicleBluetoothConnectSuccess(scanResult);
      }
      // 连接失败
      throw LxException(local.ble_connect_failed);
    });
  }

  // 开始连接【蓝牙】
  // 停止扫描，是否跳过idle状态，【当连接指定设备时，可能需要跳过idle状态，保证搜索连接的连续性，不会被idle所打断connecting状态】
  Future<bool> _startConnectBluetooth(
    CustomScanResult scanResult, {
    Duration? timeout,
    VoidCallback? onTimeout,
    bool isSkipIdleState = false,
  }) {
    debugPrint('开始连接: ${scanResult.device.advName}');
    // 停止扫描，连接设备
    return bluetoothMixinStopScan(
      isSkipIdleState: isSkipIdleState,
    ).then((_) {
      return VechileConnectionService.to.bluetoothConnectHelper!.connect(
        scanResult.device,
        timeout: timeout,
        onTimeout: onTimeout,
      );
    }).then((connectSuccess) {
      if (connectSuccess) {
        return bluetoothMixinConnectedSuccess(scanResult);
      } else {
        return Future(() => false);
      }
    });
  }

  // 蓝牙连接成功
  Future<bool> bluetoothMixinConnectedSuccess(CustomScanResult scanResult) {
    // 初始化车辆协议
    return VechileConnectionService.to
        .initializeVehicleProtocol(scanResult: scanResult)
        .then((initSuccess) {
      if (initSuccess) {
        // 初始化成功，写入缓存
        return cacheMixinNewCacheVehicle(scanResult).then((rspVehicleModel) {
          if (rspVehicleModel != null) {
            debugPrint("✅✅✅ 蓝牙连接成功，写入缓存完成: ${rspVehicleModel.toMap()}");
            return true;
          } else {
            return false;
          }
        });
      }
      throw LxException(local.device_type_not_supported);
    });
  }

  // 断开连接
  Future<void> bluetoothMixinDisconnect() {
    return VechileConnectionService.to.bluetoothConnectHelper!.disconnect();
  }
}
